package me.yricky.chart.base

class Dataset<T>(
    val name:String,
    val data:List<T>
)

sealed class Datasets<T>(
    val datasets: List<Dataset<T>>
)
class CoordinateDatasets<T>(
    datasets: List<Dataset<T>>,
    val dataXValue:(T)->Number,
    val dataYValue:(T)->Number,
) :Datasets<T>(datasets.map { orig ->
    Dataset(orig.name,orig.data.sortedBy {
        dataXValue(it).toDouble()
    })
}){
    val xRanges by lazy {
        datasets.associate {
            Pair(
                it.name,
                DataRange(
                    it.data.firstOrNull()?.let(dataXValue)?.toDouble() ?: 0.0,
                    it.data.lastOrNull()?.let(dataXValue)?.toDouble() ?: 0.0
                )
            )
        }
    }

    val xRange by lazy {
        xRanges.values.merge()
    }

    val yRanges by lazy {
        datasets.associate {
            Pair(
                it.name,
                run {
                    var min = it.data.firstOrNull()?.let { item ->
                        dataYValue(item)
                    }?.toDouble() ?: 0.0
                    var max = min
                    it.data.forEach { item ->
                        val v = dataYValue(item).toDouble()
                        if(v < min){
                            min = v
                        }
                        if(v > max){
                            max = v
                        }
                    }
                    Pair(min,max)
                }
            )
        }
    }

    val yRange by lazy {
        yRanges.values.merge()
    }

    fun isEmpty() = datasets.isEmpty() || datasets.all { it.data.isEmpty() }
}